//
//  LRXregView.m
//  路人侠
//
//  Created by zhangxulong on 2/18/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXPhoneNumView.h"
#import "AFNetworking.h"
#import "LRXRegularExpression.h"
@interface LRXPhoneNumView()<UITextFieldDelegate>
@property (nonatomic,weak) UITextField * phoneText;
@property (nonatomic,weak) UITextField * authCodeText;
@property (nonatomic,weak) UIButton * getAuthCodeBtn;
@property (nonatomic,assign) BOOL verify;
@property (nonatomic,weak) CADisplayLink * link;
@property (nonatomic,assign) NSInteger timer;
@end
@implementation LRXPhoneNumView

+ (instancetype)layoutPhoneNumSubView
{
    return [[LRXPhoneNumView alloc]initSubViews];
}

- (instancetype)initSubViews
{
    if (self = [super init]) {
        self.backgroundColor =[UIColor clearColor];
        self.textFiels = [NSMutableArray array];
        CGFloat minX =  37 * wScale;
        CGFloat fontTextSize = 30 * hScale;
        self.timer = 60;
        
        CGFloat viewW = MainScreenW * 0.7;
        CGFloat lineW = viewW - 2 * minX;
        self.verify = NO;
        
        UIView * contentView = [[UIView alloc]init];
        contentView.backgroundColor = [UIColor whiteColor];
        contentView.frame = CGRectMake(112 * wScale,0, viewW, 315 * hScale);
        contentView.layer.cornerRadius = 10 * hScale;
        
        UITextField * phoneText = [[UITextField alloc]init];
        phoneText.delegate = self;
        phoneText.tag = 1110;
        phoneText.keyboardType = UIKeyboardTypeDefault;
        phoneText.returnKeyType = UIReturnKeyNext;
        CGFloat phoneTextY = 75 * hScale;
        phoneText.placeholder = @"请输入注册手机号";
        phoneText.font = [UIFont systemFontOfSize:fontTextSize];
        phoneText.frame = CGRectMake(minX, phoneTextY, lineW, 27 * hScale);
        self.phoneText = phoneText;
        
        UIImageView * lineView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"line"]];
        CGFloat lineViewY = CGRectGetMaxY(phoneText.frame) + 10 * hScale;
        lineView.frame = CGRectMake(minX, lineViewY, lineW, 2 * hScale);
        
        UITextField * authCodeText = [[UITextField alloc]init];
        authCodeText.frame = CGRectMake(minX, lineViewY + 40 * hScale, lineW, 27 * hScale);
        authCodeText.placeholder = @"验证码";
        authCodeText.font = phoneText.font;
        authCodeText.tag = 1 + 1110;
        authCodeText.keyboardType = UIKeyboardTypeNumberPad;
        
        self.authCodeText = authCodeText;
        
        
        UIImageView * lineView2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"line"]];
        CGFloat lineView2Y = CGRectGetMaxY(authCodeText.frame) + 10 * hScale;
        lineView2.frame = CGRectMake(minX, lineView2Y, lineW, 2 * hScale);
        
        UIButton * getAuthCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        getAuthCodeBtn.layer.cornerRadius = 5 * hScale;
        [getAuthCodeBtn addTarget:self action:@selector(getAuthcode) forControlEvents:UIControlEventTouchUpInside];
        [getAuthCodeBtn setTitle:@"获取" forState:UIControlStateNormal];
        [getAuthCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        getAuthCodeBtn.titleLabel.font = [UIFont systemFontOfSize:20 * hScale];
        getAuthCodeBtn.backgroundColor =  mainColor;
        
        CGFloat getAuthCodeBtnX = CGRectGetMaxX(authCodeText.frame) - 75 * wScale;
        CGFloat getAuthCodeBtnY = CGRectGetMaxY(lineView2.frame) - 50 * hScale;
        getAuthCodeBtn.frame = CGRectMake(getAuthCodeBtnX, getAuthCodeBtnY, 75 * wScale, 45 * hScale);
        self.getAuthCodeBtn = getAuthCodeBtn;
        
        //下一个界面
        UIButton * nextBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [nextBtn setImage:[UIImage imageNamed:@"nextBtnImage"] forState:UIControlStateNormal];
        CGFloat nextBtnY = lineView2Y + 50 * hScale;
        CGFloat nextBtnX = CGRectGetMaxX(lineView.frame) - 30 * wScale;
        nextBtn.frame = CGRectMake(nextBtnX, nextBtnY, 30 * wScale, 30 * wScale);
        [nextBtn addTarget:self action:@selector(nextAuthView) forControlEvents:UIControlEventTouchUpInside];
        
        [contentView addSubview:nextBtn];
        [contentView addSubview:phoneText];
        [contentView addSubview:authCodeText];
        [contentView addSubview:lineView];
        [contentView addSubview:lineView2];
        [contentView addSubview:getAuthCodeBtn];
        
        [self.textFiels addObject:phoneText];
        [self.textFiels addObject:authCodeText];
        
        [self addSubview:contentView];

    }
    
    return self;
}
- (void)nextAuthView
{
    [self endEditing:YES];
    if([LRXRegularExpression regularExpression:self.phoneText.text withPattern:@"0?(13|14|15|18)[0-9]{9}"])
    {
        [MBProgressHUD showMessage:nil];
        [self verifyAuthCode];
    }
    else
        [MBProgressHUD showError:@"请输入正确格式的手机号"];
    
}
- (void)verifyAuthCodeAndCounts
{
    if (self.verify == YES) {
        self.phoneNum = self.phoneText.text;
        if ([self.phoneDelegate respondsToSelector:@selector(changCurView:)]) {
            [self.phoneDelegate changCurView:1];
        }
    }
    else
        [MBProgressHUD showError:@"验证码错误"];
}

//获取验证码
- (void)getAuthcode
{
    
    if (![LRXRegularExpression regularExpression:self.phoneText.text withPattern:@"0?(13|14|15|18)[0-9]{9}"]) {
        [MBProgressHUD showError:@"请输入正确的手机号"];
    }else
    {
        NSDictionary * parmes = @{@"account":self.phoneText.text,@"imei":registrationID};
        AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
        [manger POST:getAuthCodeUrl parameters:parmes progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSInteger statusCode  = [responseObject[@"data"][@"status_code"] integerValue];
            if (statusCode == 3) {
                [MBProgressHUD showError:@"该手机号已经注册,请直接登录"];
                
            }
            
            if (statusCode == 2) {
                [MBProgressHUD showError:@"短信发送失败"];
               
            }
            //成功 获取验证码成功
            if (statusCode == 1) {
                //添加定时器
                [self addDisplayLink];
                self.getAuthCodeBtn.enabled = NO;
                
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD showError:@"网络连接发生错误"];
        }];
    }
 
}


//验证验证码
- (void)verifyAuthCode
{
    NSDictionary * parmes = @{@"account":self.phoneText.text,@"authcode":self.authCodeText.text};
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    [manger POST:verifyAuthCodeUrl parameters:parmes progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            NSInteger statusCode  = [responseObject[@"data"][@"status_code"] integerValue];
            if (statusCode == 1){
                self.verify = YES;
                [self.getAuthCodeBtn setTitle:@"获取" forState:UIControlStateNormal];
                [self removeDisplayLink];
                [self verifyAuthCodeAndCounts];
            }
            else
            {
                [MBProgressHUD showError:@"验证码错误"];
                self.verify = NO;
            }
        });

       
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络错误"];
        self.verify = NO;
        [self verifyAuthCodeAndCounts];
    }];
    
    
}
//添加定时器
- (void)addDisplayLink
{
    //创建一个CADisplayLink定时器
    CADisplayLink * link = [CADisplayLink displayLinkWithTarget:self selector:@selector(changeBtnText)];
    // 标识间隔多少帧调用一次selector 方法
    link.frameInterval = 60;
    //加入主循环中
    [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    self.link = link;
}
//移除定时器
- (void)removeDisplayLink
{
    [self.link removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)changeBtnText
{
    
    self.timer -= 1;
    [self.getAuthCodeBtn setTitle:[NSString stringWithFormat:@"%ld",self.timer] forState:UIControlStateNormal];
    
    // 移除定时器 可以重新添加新的定时器了
    if (self.timer <= 0) {
        self.getAuthCodeBtn.enabled = YES;
        [self.getAuthCodeBtn setTitle:@"获取" forState:UIControlStateNormal];
        self.timer = 60;
        [self removeDisplayLink];
    }
}
- (void)dealloc
{
    [self removeDisplayLink];
}

//------------------------------------------------------------textField的代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.authCodeText becomeFirstResponder];
    return YES;
}
//----------------------------------------------------------------------------
@end
